package com.indusfo.spc.client.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import com.indusfo.spc.service.RuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.indusfo.spc.client.mapper.ClientBatchFinishMapper;
import com.indusfo.spc.client.pojo.ClientBatchFinish;
import com.indusfo.spc.client.service.ClientBatchFinishService;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.BatchMapper;
import com.indusfo.spc.pojo.Batch;
import com.indusfo.spc.service.BarCodeRules;
import com.indusfo.spc.untlis.StringUtils;

/**
 * 客户端批次报工
 * 
 * @author zhengd
 *
 */
@Service
public class ClientBatchFinishServiceImpl implements ClientBatchFinishService {
	@Resource
	private ClientBatchFinishMapper clientBatchFinishMapper;
	@Resource
	private BarCodeRules barCodeRules;
	@Resource
	private BatchMapper batchMapper;
	@Resource
	private RuleService ruleService;
	/**
	 * 客户端批次报工新增
	 */
	@Override
	public String saveClientBatchFinish(ClientBatchFinish clientBatchFinish) {
		if (clientBatchFinish.getOrderId() == null) {
			throw new ParamsErrorException("请传入任务单ID");
		}
		// 判断没有批次ID时自动生成一个ID
		if (clientBatchFinish.getBatchId() == null) {
			Batch batch = new Batch();
			// 设置任务单ID
			batch.setOrderId(clientBatchFinish.getOrderId());
			// 设置生成批号数量为1
			Integer num = 1;
			// 声明接收批号的集合（调用web端接口才这么写的）
			List<String> list = new ArrayList<>();
			// 调用web端接口生成批号
			Integer ruleId = batchMapper.queryRuleId(batch.getOrderId());
			list = ruleService.batchRule(batch.getOrderId(),num);
//			list = barCodeRules.calculate(ruleId, num);
			// 将生成的批号设置到对象中
			clientBatchFinish.setBatchCode(list.get(0));
			// 新增批次
			clientBatchFinishMapper.saveClientBatch(clientBatchFinish);
			// 将新增的批次ID放入报工对象
			clientBatchFinish.setBatchId(clientBatchFinish.getBatchId());
		}
		if (clientBatchFinish.getFinishNum() == null) {
			throw new ParamsErrorException("请传入完工数量");
		}
		// 不良数没有就设置为0
		if (clientBatchFinish.getNotQualifyNum() == null) {
			clientBatchFinish.setNotQualifyNum(0);
		}
		// 保存报工
		clientBatchFinishMapper.saveClientBatchFinish(clientBatchFinish);
		// 返回批号给前端
		return clientBatchFinish.getBatchCode();
	}

	/**
	 * 客户端批次报工根据批号查询基本信息
	 */

	@Override
	public ClientBatchFinish queryClientBatchFinishByBatchCode(String batchCode) {
		if (StringUtils.isBlank(batchCode)) {
			throw new ParamsErrorException("请传入批号");
		}
		return clientBatchFinishMapper.queryClientBatchFinishByBatchCode(batchCode);
	}

	/**
	 * 根据任务单ID查询已报工数量
	 */

	@Override
	public ClientBatchFinish queryClientFinishNumByOrderId(Integer orderId) {
		return clientBatchFinishMapper.queryClientFinishNumByOrderId(orderId);
	}

	/**
	 * 客户端批次报工查询当天报工信息
	 * 
	 */
	@Override
	public List<ClientBatchFinish> queryClientBatchFinishByCreateDate() {
		return clientBatchFinishMapper.queryClientBatchFinishByCreateDate();
	}

}
